package com.seednia.foundation.framework.dto;

import java.io.IOException;
import java.util.HashMap;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import org.codehaus.jackson.map.ObjectMapper;

import com.seednia.foundation.framework.util.StringUtils;

/**
 * This class is used to send query parameter other than criteria such as 
 * paging to the DAO.
 *  
 * If needed, the caller can send further information including sort (ORDER BY)
 * 
 * @author Young Suk Ahn
 *
 */
@XmlRootElement(name = "QueryParams", 
namespace = "http://seednia.com/foundation/1.0")
@XmlType(name = "QueryParams")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class QueryParams extends HashMap<String, Object> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 9023871963458061852L;

	public static enum Operator {
        OR,
        AND
    }
	
	private Operator defaultOperator = Operator.AND; // query operator
	private int offset=0;
	private int max = 10;
	
	boolean retrieveCount = true; // true means execute count statement
	
	public QueryParams()
	{
	}
		
	public QueryParams(int offset, int max)
	{
		this.offset = offset;
		this.max = max;
	}
	
	public Operator getDefaultOperator() {
		return defaultOperator;
	}
	public void setDefaultOperator(Operator defaultOperator) {
		this.defaultOperator = defaultOperator;
	}

	public int getOffset() {
		return offset;
	}
	public void setOffset(int offset) {
		this.offset = offset;
	}
	public int getMax() {
		return max;
	}
	public void setMax(int max) {
		this.max = max;
	}
	public boolean isRetrieveCount() {
		return retrieveCount;
	}
	public void setRetrieveCount(boolean retrieveCount) {
		this.retrieveCount = retrieveCount;
	}
	
	public void setParamsText(String paramsText) {
		if (this.size()> 0)
			this.clear();
		this.putAll(StringUtils.getQueryMap(paramsText));
	}
	
	public String getParamsText()
	{
		return StringUtils.getQueryString(this);
	}
	
	public Object get(String key, Object defaultVal)
	{
		return (super.containsKey(key)) ? super.get(key) : defaultVal; 
			
	}
	
	// Used by the REST framework to convert JSONP to object
    public static QueryParams fromString(String jsonStr)
    {
    	ObjectMapper mapper = new ObjectMapper();
    	QueryParams retval = null;
        try {
        	retval = mapper.readValue(jsonStr, QueryParams.class);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
        return retval;
    }
}
